<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {createMessage, queryAllMessages} from "@/api/message-api.ts";
import {ElMessage} from "element-plus";

const tableData = ref([]);
const dialogFormVisible = ref(false);
const form = reactive({
  message: "",
});

onMounted(async () => {
  try {
    tableData.value = await queryAllMessages();
  } catch (error) {
    console.error('Failed to fetch messages:', error);
  }
});

const addMessage = () => {
  dialogFormVisible.value = true;
  form.message = ""; // 清空表单
}

const saveMessage = async () => {
  try {
    await createMessage(form);
    ElMessage.success("新增成功")
    dialogFormVisible.value = false;
    await refreshTable();
  } catch (error) {
    console.error('Failed to create message:', error);
  }
}

async function refreshTable() {
  try {
    const messages = await queryAllMessages();
    tableData.value = messages;
  } catch (error) {
    console.error('Failed to refresh table:', error);
  }
}
</script>

<template>
  <h1 style="text-align: center">This is Home Page</h1>
  <el-button type="primary" @click="addMessage">新增</el-button>
  <el-table :data="tableData" border style="width: 500px; padding-top: 20px">
    <el-table-column prop="id" label="Id" width="250" />
    <el-table-column prop="message" label="Message" width="250" />
  </el-table>

  <el-dialog v-model="dialogFormVisible" title="新增数据" width="500">
    <el-form :model="form">
      <el-form-item label="message:" :label-width="90">
        <el-input type="textarea" v-model="form.message" autocomplete="off" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible.value = false">取消</el-button>
        <el-button type="primary" @click="saveMessage">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>
